package com.tao.util.pack;

import java.util.List;

import com.google.gson.Gson;
import com.tao.util.ThreadLostener;
import com.tao.util.Utils;
import com.tao.util.pack.MsgBean.AddMsgListEntity;

public class HeartBeatThread extends Thread {

	private HttpClient hc = HttpClient.getInstance();
	private StringSubClass ss = new StringSubClass();
	private Gson gson = new Gson();
	private boolean beat = true;
	private OnNewMsgListener mNewMsgListener;
	private OnExitMsgListener mExitMsgListener;
	private OnStatsMsgListener mStatsMsgListener;
	private WeChatClass wechat;

	public interface OnNewMsgListener {// 接收新消息监听器
		void onNewMsg(String text);

		void startBeat(String uin);
	}

	public interface OnExitMsgListener {// 用户退出监听器
		void onExitMsg(String text);
		
	}

	public interface OnStatsMsgListener {// 用户心跳状态监听器
		void onStatsMsg(String text);

	}

	public HeartBeatThread(WeChatClass wechat) {
		this.wechat = wechat;
	}

	public void setmNewMsgListener(OnNewMsgListener mNewMsgListener) {
		this.mNewMsgListener = mNewMsgListener;
	}

	public void setmExitMsgListener(OnExitMsgListener mExitMsgListener) {
		this.mExitMsgListener = mExitMsgListener;
	}

	public void setmStatsMsgListener(OnStatsMsgListener mStatsMsgListener) {
		this.mStatsMsgListener = mStatsMsgListener;
	}
	

	public HttpClient getHc() {
		return hc;
	}

	public void setHc(HttpClient hc) {
		this.hc = hc;
	}

	public StringSubClass getSs() {
		return ss;
	}

	public void setSs(StringSubClass ss) {
		this.ss = ss;
	}

	public Gson getGson() {
		return gson;
	}

	public void setGson(Gson gson) {
		this.gson = gson;
	}

	public boolean isBeat() {
		return beat;
	}

	public void setBeat(boolean beat) {
		this.beat = beat;
	}

	public WeChatClass getWechat() {
		return wechat;
	}

	public void setWechat(WeChatClass wechat) {
		this.wechat = wechat;
	}

	public OnNewMsgListener getmNewMsgListener() {
		return mNewMsgListener;
	}

	public OnExitMsgListener getmExitMsgListener() {
		return mExitMsgListener;
	}

	public OnStatsMsgListener getmStatsMsgListener() {
		return mStatsMsgListener;
	}

	@Override
	public void run() {
		if (mNewMsgListener != null) {
			mNewMsgListener.startBeat(wechat.wxuin);
		}
		if(beat==false){
			String name = "close"+this.getName();
			if(ThreadLostener.heartBeatThreadMap.containsKey(name)){				
				ThreadLostener.heartBeatThreadMap.remove(name);
			}
			System.out.println("----------------移除线程----------"+name);
		}
		
		while (beat) {

			System.out.println(wechat.wxuin + "心跳...." + Utils.getSystemTime());

			// window.synccheck={retcode:"0",selector:"7"}
			String syncResult = hc.get(
					"https://webpush2.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?skey="
							+ wechat.skey + "&sid=" + wechat.wxsid + "&uin="
							+ wechat.wxuin + "&deviceId="+Utils.getDeviceID()
							+ "&synckey=" + wechat.keyString + "&r="
							+ System.currentTimeMillis() + "&_="
							+ System.currentTimeMillis(), wechat.cookie);
			
			System.err.println(syncResult);

			// 如果网络超时重新请求网络
			if (null == syncResult) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {

				}
				continue;
			}

			String selector;
			String retcode;
			try {
				retcode = ss.subStringOne(syncResult, "retcode:\"", "\",");
				selector = ss.subStringOne(syncResult, "selector:\"", "\"}");
			} catch (Exception e) {
				continue;
			}

			// 线程关闭
			if (retcode.equals("1101")) {
				String syncResult1 = hc.get(
						"https://webpush2.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?skey="
								+ wechat.skey + "&sid=" + wechat.wxsid
								+ "&uin=" + wechat.wxuin
								+ "&deviceId="+Utils.getDeviceID() + "&synckey="
								+ wechat.keyString + "&r="
								+ System.currentTimeMillis() + "&_="
								+ System.currentTimeMillis(), wechat.cookie);

				// 如果网络超时重新请求网络
				if (null == syncResult1) {
					continue;
				}

				String retcode1;
				try {
					retcode1 = ss
							.subStringOne(syncResult1, "retcode:\"", "\",");
				} catch (Exception e) {
					continue;
				}

				if (retcode1.equals("1101")||retcode1.equals("1100")) {

					beat = false;
					if (mNewMsgListener != null) {
						mExitMsgListener.onExitMsg(wechat.wxuin + ":" + retcode
								+ ":" + Utils.getSystemTime());
					}
				}
			}
			// 状态监控
			mStatsMsgListener.onStatsMsg(wechat.wxuin + ":" + retcode + ":"
					+ Utils.getSystemTime());

			if (!selector.equals("0")) {// 有消息
				if (mNewMsgListener != null) {
					// 获取新消息
					String data2 = "{\"BaseRequest\":{\"Uin\":\""
							+ wechat.wxuin
							+ "\",\"Sid\":\""
							+ wechat.wxsid
							+ "\",\"Skey\":\""
							+ wechat.skey
							+ "\",\"DeviceID\":\"e982189146506998\"},\"SyncKey\":"
							+ wechat.gson.toJson(wechat.initbean.getSyncKey())
							+ ",\"rr\":" + System.currentTimeMillis() + "}";
					String newMsg = hc.post(wechat.baseUrl + "/webwxsync?sid="
							+ wechat.wxsid + "&skey=" + wechat.skey
							+ "&pass_ticket=" + wechat.pass_ticket,
							wechat.cookie, data2);//
					// 同步键更新
					if (null != newMsg) {
						wechat.syncKeys(newMsg);

						// 获取消息
						MsgBean msgBean = gson.fromJson(newMsg, MsgBean.class);
						List<AddMsgListEntity> msgList = msgBean
								.getAddMsgList();
						for (AddMsgListEntity addMsgListEntity : msgList) {
							if (addMsgListEntity.getFromUserName().startsWith(
									"@@")) {// 只处理群消息
								String msg = addMsgListEntity.getContent();
								msg = msg.substring(msg.indexOf("<br/>") + 5);
								mNewMsgListener.onNewMsg(msg);
							}
						}// for
					}
				}
			}
			try {
				// 线程休眠25秒再请求网络
				sleep(25000);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}// while
		
		System.out.println("-------------- 心跳已关闭 ----------------------");
	}
}
